<template>
	<contents
		:heightInclude="['tabBar', 'navBar']"
		class="search_page"
		:nullData="goodsList.length == 0"
		nullImg="http://img.druglots.cn/null_data.png"
	>
		<view
			class="search"
			:style="'height: 100vh'"
		>
			<u-navbar is-fixed :custom-back="onClickBackBtn">
				<view class="search_wrap">
					<u-search
						:placeholder="$t('locales.placeholderGoodsName')"
						v-model="form.keyword"
						:action-style="{
							height: '60rpx',
							lineHeight: '60rpx'
						}"
						:action-text="$t('locales.search')"
						@search="onClickCellItem(form.keyword || '')"
						@custom="onClickCellItem(form.keyword || '')"
						@focus="onClickSearchInput"
						
					></u-search><!--@change="getRelatedKeyword"-->
				</view>
			</u-navbar>
			<view
				class="history_search"
				v-if="historyList.length !== 0"
			>
				<view class="title">
					<text class="title_name">{{$t('locales.historySearch')}}</text>
					<view class="title_opt" @click.stop="delAll">
						<u-icon name="trash" color="#7F7F95" size="28"></u-icon>
						<text>{{$t('locales.eliminate')}}</text>
					</view>
				</view>
				<view class="history_list">
					<view
						class="list_item"
						v-for="(item, index) in historyList"
						:key="item"
					>
						<u-tag
							:text="item"
							mode="dark"
							bg-color="#F7F7F7"
							color="#222"
							closeable
							@click="itemClick(item)"
							@close="del(index)"
						/>
					</view>
				</view>
			</view>
			<view
				class="history_search"
				style="border: none"
			>
				<view class="title">
					<text class="title_name">{{$t('locales.recommendedSearch')}}</text>
					<text class="title_opt"></text>
				</view>
				<view class="history_list">
					<view
						class="list_item"
						v-for="item in hotSearchList"
						:key="item.id"
					>
						<u-tag
							@click="itemClick(item.word)"
							:text="item.word"
							mode="dark"
							bg-color="#F7F7F7"
							color="#222"
						/>
					</view>
				</view>
			</view>
		</view>
		<view class="block"></view>

		<scroll-view v-if="isShowRelatedKeyword" class="related-keyword">
			<u-cell-group>
				<u-cell-item
					v-for="item in relatedKeywordList"
					:key="item"
					:title="item"
					:arrow="false"
					@click="onClickCellItem(item)"
				/>
			</u-cell-group>
		</scroll-view>
		<GoodsLists v-if="false" :type="4" v-model="goodsList" :more="false" />
	</contents>
</template>

<script>
import { getHotSearch, getRelatedKeywordAction } from '@/api/http/home'
import { getStoregoodList } from '@/api/http/store'
import GoodsLists from '@/components/goodsList'
import * as api from '@/api/http/home'

export default {
	components: {
		GoodsLists: GoodsLists
	},
	data() {
		return {
			form: {
				keyword: ''
			},
			pageNo: 1,
			shouList: false,
			goodsList: [],
			hotSearchList: [],
			historyList: [],

			timer: null,

			relatedKeywordList: [],

			isShowRelatedKeyword: false,
			routerParams: {}
		}
	},
	onLoad(opt) {
		this.routerParams = opt
		this.form.keyword = opt.keyword

		if (this.routerParams.getHot === '1') {
			this.getHot()
		} else {
			this.getKeywords()
		}

		if (this.form.keyword) {
			this.isShowRelatedKeyword = true
			this.getRelatedKeyword()
			return
		}

		if (opt.placeholder) {
			this.form.keyword = opt.placeholder
			this.isShowRelatedKeyword = false
		}
		
	},
	onShow() {
		// 从缓存取出历史记录,H5是cookie因此已字符串的形式存入
		if (this.$storage.get('searchList')) {
			this.historyList = this.$storage.get('searchList').split(',')
		}
	},
	onReachBottom() {
		this.pageNo += 1
		// this.getData(this.pageNo)
	},
	methods: {
		async getKeywords() {
			const res = await api.getKeywordInfo()

			if (res.code === 200) {
				this.hotSearchList = res.data[this.routerParams.modelId]
			} else {
				return uni.showToast({
					title: res.message,
					icon: 'none'
				})
			}
		},

		searchFocus() {
			this.shouList = true
		},
		getData(page = 1) {
			this.pageNo = page
			getStoregoodList({
				...this.form,
				pageNo: page,
				pageSize: 300,
				domainPrefix: this.$store.getters.domainPrefix
			}).then(res => {
				if (res.code === 200) {
					this.shouList = false
					this.setHistory(this.form.keyword)
					if (page !== 1) {
						this.goodsList.concat(res.data.records)
					} else {
						this.goodsList = res.data.records
					}
				} else {
					uni.showToast({
						icon: 'none',
						title: res.message
					})
				}
			})
		},
		getHot() {
			getHotSearch({
				domainPrefix: this.$store.getters.domainPrefix || ''
			}).then(res => {
				if (res.code === 200) {
					this.hotSearchList = res.data
					// if (res.data.length > 0) this.form.keyword = res.data[0].word || ''
				} else {
					uni.showToast({
						icon: 'none',
						title: res.message
					})
				}
			})
		},
		itemClick(val) {
			this.form.keyword = val
			this.getData(1)
		},
		// 储存历史记录
		setHistory(val) {
			const searchList = this.$storage.get('searchList') || ''
			let oldList = searchList.split(',')
			if (val.length > 20) {
				oldList.push(val.substring(0, 20))
			} else {
				oldList.push(val)
			}
			// 去重
			oldList = Array.from(new Set(oldList))
			// 去空
			oldList.map((item ,index) => {
				if (item == '')  oldList.splice(index, 1)
			})
			this.$storage.set('searchList', oldList.join(','))
			this.historyList = oldList
		},
		// 删除全部
		delAll() {
			this.$storage.set('searchList', '')
			this.historyList = []
		},
		// 删除单个
		del(index) {
			let oldList = this.$storage.get('searchList').split(',')
			oldList.splice(index, 1)
			this.$storage.set('searchList', oldList.join(','))
			this.historyList = oldList
		},

		throttle(fn = function() {}, time) {
			let timer = null

			return (arg) => {
				clearTimeout(timer)

				timer = setTimeout(() => {
					fn(arg)
				}, time)
			}
		},

		getRelatedKeyword(word) {
			clearTimeout(this.timer)

			if (word === '') return

			this.timer = setTimeout(() => {
				this.handleRelatedKeywordAction(word)
			}, 300)
		},

		async handleRelatedKeywordAction(word) {
			const res = await getRelatedKeywordAction({
				key: word,
				domainPrefix: this.$store.getters.domainPrefix
			})

			if (res.code === 200) {
				if (!res.data.length) {
					this.isShowRelatedKeyword = false
					return
				}

				this.relatedKeywordList = res.data				
			} else {
				return uni.showToast({
					title: res.message,
					icon: 'none'
				})
			}
		},

		onClickCellItem(item) {
			uni.reLaunch({
				url: '/pages/sort/index?keyword=' + item
			})
		},

		onClickBackBtn() {
			if (this.isShowRelatedKeyword) {
				this.isShowRelatedKeyword = false
				return
			}
			uni.navigateBack()
		},

		onClickSearchInput() {
			this.isShowRelatedKeyword = true

			if (this.form.keyword) {
				this.getRelatedKeyword()
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.search_page {
	.search {
		position: absolute;
		width: 100%;
		height: 100%;
		left: 0;
		top: 0;
		background-color: #f7f4f8;
		z-index: 99;
	}
	.block {
		height: calc(var(--status-bar-height) + 44px);
	}
	.search_wrap {
		padding-right: 20rpx;
		flex: 1;
	}
	.history_search {
		padding: 0 30rpx 30rpx 30rpx;
		border-bottom: 1px solid #dddddd;
		background-color: #fff;
		.title {
			height: 70rpx;
			align-items: center;
			display: flex;
			justify-content: space-between;
			font-size: 26rpx;
			.title_name {
				font-weight: bold;
			}
			.title_opt {
				color: #7f7f95;
			}
		}
	}
	.history_list {
		.list_item {
			display: inline-block;
			margin: 10rpx;
		}
	}

	.related-keyword {
		position: relative;
		height: calc(100vh - 44rpx);
		background: rgb(247, 244, 248);
		z-index: 100;
	}
}
</style>
